from flask import Blueprint, render_template, jsonify, request

from models.entity.device_with_sensor import DeviceWithSensor
from models.entity.sensor_type import SensorType
from models.entity.sensor import Sensor
import json
import uuid

"""
传感器
"""
mod = Blueprint("iot_sensor", __name__, url_prefix="/iot/sensor", template_folder="templates",
                static_folder="static")


@mod.route("/", methods=["GET"])
def sensor_index(*args, **kargs):
    return render_template('/admin/core/sensor_index.html', **locals())

@mod.route("/type", methods=["GET"])
def sensor_type_index(*args, **kargs):
    # 没有sensor_type_index.html 这个模板
    return render_template('/admin/core/sensor_type_index.html', **locals())


@mod.route('/get_all_by_device_id/', methods=['GET', 'POST'])
def get_sensor_by_device():
    """得到传感器"""
    """传入的是设备的id"""
    """
    {
        "id": 2
    }
    """
    print('kaishi')
    if request.method == 'POST':
        print('post')
        receive = request.data
        print(111,receive)  # b '' 空字节
        dict = json.loads(receive.decode("utf-8"))
        print(222,dict)
        id = dict['id']
        sensors = Sensor.get_sensors_by_device_id(id)
        data = []
        tmp = {}
        for item in sensors:
            data.append(item.get_dic())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        return '123'


@mod.route('/get_all_by_sensor_type_id/', methods=['GET', 'POST'])
def get_sensor_by_device_id():
    """得到传感器"""
    """传入的是传感器类型的id"""
    """
    {
        "id": 2
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        sensors = Sensor.query.filter_by(sensor_type_id=id).order_by('dis_order').all()
        data = []
        tmp = {}
        for item in sensors:
            data.append(item.get_dic())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        return '333333sensor'


@mod.route('/get_all_by_sensor_group_id/', methods=["POST"])
def get_all_by_sensor_group_id():
    """
    根据传感器分组id获取此分组下的所有传感器
    """

    """
    {
        "id":id    // 传感器分组id
    }
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json格式错误"
        }
    if "id" not in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "id不在json中"
        }
        return jsonify(error_msg)
    else:
        id = data["id"]
    all_sensor = Sensor.query.filter_by(sensor_group_id=id).all()
    rdic = {}
    rdic["success"] = 1
    rdic["error_code"] = None
    rdic["error_msg"] = None
    rdic["data"] = []
    for item in all_sensor:
        rdic["data"].append(item.get_dic())
    return jsonify(rdic)


@mod.route('/del/', methods=['GET', 'POST'])
def del_sensor():
    """删除传感器"""

    """
    {
	"id":2
    }
    """
    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = int(dict['id'])
        data = []
        sensor = Sensor.get_sensor_by_id(id)
        if not sensor:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "没有查找到当前记录"
            tmp['data'] = data
            return jsonify(tmp)
        # 删除sensor与device的中间表信息
        for item in DeviceWithSensor.query.filter_by(sensor_id=sensor.id).all():
            if item.delete() is False:
                tmp['success'] = 0
                tmp['error_code'] = -2
                tmp['error_msg'] = "未知错误"
                tmp['data'] = data
                return jsonify(tmp)
        if sensor.delete():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "未知错误"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/add/', methods=['GET', 'POST'])
def add_sensor():
    """
	{
	"name":"kddd12dk",
	"sensor_type_id":1,
	"code":"dddhttd",
    "eng_unit":"ggg",
	"description":"fff",
	"status":1,
	"dis_order":3,
	"h":900,
	"l":10,
    "hh":950,
    "ll":5,
	"range_max":1000,
	"range_min":10,
	"remote_host_id":1
    }
    """
    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        data = []
        if "sensor_type_id" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "sensor type is null"
            tmp['data'] = data
            return jsonify(tmp)
        sensor_type_id = dict['sensor_type_id']
        if "name" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "Name is null"
            tmp['data'] = data
            return jsonify(tmp)
        name = dict['name']
        range_max = dict['range_max']
        range_min = dict['range_min']
        h = dict['h']
        l = dict['l']
        hh = dict['hh']
        ll = dict['ll']
        description = dict['description']
        eng_unit = dict['eng_unit']
        dis_order = dict['dis_order']
        data_type = dict['data_type']
        topic = dict['topic']
        client_id = dict['client_id']
        is_exp = dict['is_exp']
        exp = dict['exp']
        status = dict['status']
        sensor_group_id = dict['sensor_group_id']
        remote_host_id = dict['remote_host_id']
        icon = dict['icon']
        if 'device_id' not in dict:
            device_id = None
        else:
            device_id = dict['device_id']
        if Sensor.get_sensor_by_name(name):
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "Same name exists"
            tmp['data'] = data
            return jsonify(tmp)
        sensor = Sensor()
        sensor.name = name
        sensor.sensor_type_id = int(sensor_type_id)
        sensor.description = description
        sensor.eng_unit = eng_unit
        sensor.dis_order = int(dis_order)
        sensor.status = int(status)
        sensor.h = h
        sensor.l = l
        sensor.hh = hh
        sensor.ll = ll
        sensor.range_max = range_max
        sensor.range_min = range_min
        sensor.data_type = data_type
        # sensor.topic = topic
        # 临时更改: 给予topic默认随机字符串
        sensor.topic = uuid.uuid4().hex
        sensor.client_id = client_id
        sensor.is_exp = is_exp
        sensor.exp = exp
        sensor.sensor_group_id = sensor_group_id
        sensor.remote_host_id = remote_host_id
        sensor.icon = icon
        sensor.device_id = device_id
        if sensor.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "unknown Error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_sensor():
    """这个函数的主要功能是编辑传感器"""
    """
    {
	"name":"kddd12dk",
	"sensor_type_id":1,
	"code":"dddhttd",
	"description":"fff",
	"status":1,
	"dis_order":3,
	"h":900,
	"l":10,
    "hh":950,
    "ll":5,
    "range_max":1000,
	"range_min":0,
	"eng_unit":"ggg",
	"source_addr":"192.162.0.4"
    }
    """
    if request.method == 'POST':
        tmp = {}
        data = []
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = int(dict['id'])
        name = dict['name']
        sensor_type_id = dict['sensor_type_id']
        description = dict['description']
        hh = dict['hh']
        ll = dict['ll']
        h = dict['h']
        l = dict['l']
        range_max = dict['range_max']
        range_min = dict['range_min']
        eng_unit = dict['eng_unit']
        dis_order = dict['dis_order']
        data_type = dict['data_type']
        topic = dict['topic']
        client_id = dict['client_id']
        is_exp = dict['is_exp']
        exp = dict['exp']
        status = dict['status']
        sensor_group_id = dict['sensor_group_id']
        remote_host_id = dict['remote_host_id']
        icon = dict['icon']
        if not Sensor.get_sensor_by_id(id):
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "当前操作的记录不存在"
            tmp['data'] = data
            return jsonify(tmp)
        sensor = Sensor.get_sensor_by_id(id)
        if name != sensor.name and Sensor.get_sensor_by_name(name) is not None:
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "Same name exist"
            tmp['data'] = data
            return jsonify(tmp)
        sensor.name = name
        sensor.sensor_type_id = sensor_type_id
        sensor.description = description
        sensor.dis_order = int(dis_order)
        sensor.status = status
        sensor.hh = hh
        sensor.ll = ll
        sensor.h = h
        sensor.l = l
        sensor.range_min = range_min
        sensor.range_max = range_max
        sensor.eng_unit = eng_unit
        sensor.description = description
        sensor.is_exp = is_exp
        sensor.exp = exp
        sensor.client_id = client_id
        sensor.data_type = data_type
        sensor.remote_host_id = remote_host_id
        sensor.dis_order = dis_order
        sensor.topic = topic
        sensor.sensor_group_id = sensor_group_id
        sensor.icon = icon
        if sensor.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "unknown Error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_dict_item():
    """得到全部传感器"""
    """这个方法不合理"""
    """无需传参"""
    sensors = Sensor.query.all()
    data = []
    tmp = {}
    for item in sensors:
        data.append(item.to_dict())
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)
